﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using XRM.Security.DataAccess.Helpers;
using XRM.Security.DataAccess.Repositories.Impl;
using XRM.Security.WebUI.Helpers;

namespace XRM.Security.WebUI.Models.Report.ReportBuilder
{
    public class CertReportBuilder : ReportBuilderBase
    {
        private readonly CertRegisterRepository _certRepository;

        public override string TemplateFileName
        {
            get { return "Выданные и действующие сертификаты"; }
        }

        public CertReportBuilder( CertRegisterRepository repository )
        {
            _certRepository = repository;
        }

        public override string Create(CreateReportModel model)
        {
            var query = _certRepository.GetAll().ValidCertificates();
            if (model.Value.HasValue)
            {
                query = query.Where( s => s.IdentityCenterId == model.Value);
            }
            var certificates = query.OrderBy(s => s.UserRegister.LastName)
                .Select(s => new {s.UserRegister.FirstName, s.UserRegister.MotherName, s.UserRegister.LastName, s.IdentityCenter.IdentityCenterName,
                    s.SerialNumber, s.FromDate, s.ToDate, InfoSystems = s.CertRegisterInfoSystems.Select(g => g.InfoSystem.InfoSystemName)})
                .AsEnumerable()
                .Select( s => new CertificatesReportTypeCertificates
                    {
                        CertificationAuthority = s.IdentityCenterName,
                        FirstName = s.FirstName,
                        MiddleName = s.MotherName,
                        SecondName = s.LastName,
                        LimitationDate = String.Format("{0:dd.MM.yyyy} - {1:dd.MM.yyyy}", s.FromDate, s.ToDate),
                        SerialNumber = s.SerialNumber,
                        Systems = String.Join( "\r\n", s.InfoSystems )
                    } ).ToArray();
            var report = new CertificatesReportType
            {
                CreateDate = DateTime.Today,
                Certificates = certificates.ToArray()
            };
            
            return CreateXlsxDocument( Utils.SerializeToString( report ) );
        }
    }
}